<?php
declare (strict_types=1);

namespace app\service;

use OSS\Core\OssException;
use OSS\OssClient;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Env;
use think\facade\Filesystem;
use think\facade\Log;
use think\File;

class UploadFileService extends \think\Service
{
    /**
     * 文件校验
     * @var bool
     */
    protected $autoValidate = false;

    /**
     * 上传路径
     * @var string
     */
    protected $uploadPath;

    /**
     * 上传类型
     * @var int
     */
    protected $uploadType;

    /**
     * 发生错误时是否返回错误信息
     * @var bool
     */
    protected $returnErr = false;

    /**
     * 上传文件返回数组初始值
     * @var array
     */
    protected $uploadInfo = [
        'name' => '',
        'size' => 0,
        'type' => 'image/jpeg',
        'dir' => '',
        'thumb_path' => '',
        'image_type' => '',
        'time' => 0,
    ];

    protected $instance;

    /**
     * 上传信息
     * @var object
     */
    private static $uploadStatus;

    /**
     * 上传图片的大小 2MB 单位字节
     * @var string
     */
    protected $imageValidate = null;

    /**
     * 上传规则
     * @var array
     */
    protected $imageValidateArray = [
        'filesize' => 2097152,
        'fileExt' => ['jpg', 'jpeg', 'png', 'gif', 'pem', 'mp3', 'wma', 'wav', 'amr', 'mp4'],
        'fileMime' => ['image/jpeg', 'image/gif', 'image/png', 'text/plain', 'audio/mpeg'],
    ];
    protected $ossValidateArray = [
        ''
    ];

    protected $propsRule = [
        'returnErr' => false,
        'autoValidate' => false,
        'uploadPath' => null,
        'uploadType' => null,
    ];

    public function __construct($path)
    {
        $this->uploadPath = $path;
        $this->init();
    }

    /**
     * 初始化
     */
    protected function init()
    {
        self::$uploadStatus = new \StdClass();
        $this->extractValidate();
    }

    /**
     * 提取上传验证
     */
    protected function extractValidate()
    {
        $imageValidate = [];
        foreach ($this->imageValidateArray as $key => $value) {
            $imageValidate[] = $key . ':' . (is_array($value) ? implode(',', $value) : $value);
        }
        $this->imageValidate = implode('|', $imageValidate);
        unset($imageValidate);
    }

    /**
     * 设置上传验证
     * @param array $imageValidateArray
     * @return $this
     */
    public function setImageValidateArray(array $imageValidateArray)
    {
        if (isset($imageValidateArray['filesize']) && !is_int($imageValidateArray['filesize'])) {
            $imageValidateArray['filesize'] = 2097152;
        }
        $this->imageValidateArray = array_merge($this->imageValidateArray, $imageValidateArray);
        $this->extractValidate();
        return $this;
    }

    /**
     * 返回失败信息
     * @param $error
     * @return mixed
     */
    protected static function setError($error)
    {
        self::$uploadStatus->status = false;
        self::$uploadStatus->error = $error;
        return self::$uploadStatus;
    }

    /**
     * 返回成功信息
     * @param $path
     * @return mixed
     */
    protected static function successful($arr)
    {
        self::$uploadStatus->status = true;
        self::$uploadStatus->dir = '/uploads/' . $arr['dir'];
        self::$uploadStatus->name = $arr['name'];
        self::$uploadStatus->size = $arr['size'];
        self::$uploadStatus->type = $arr['type'];
        self::$uploadStatus->time = time();
        self::$uploadStatus->thumb_path = '';
        self::$uploadStatus->image_type = $arr['image_type'];
        self::$uploadStatus->ext = $arr['ext'];

        return self::$uploadStatus;
    }

    /**
     * 检查上传目录不存在则生成
     * @param $dir
     * @return bool
     */
    protected static function validDir($dir)
    {
        return is_dir($dir) == true || mkdir($dir, 0777, true) == true;
    }

    /**
     * @param $path
     * @param null $root
     * @return string
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/29 0029
     * @describe:生成上传文件目录
     */
    public function uploadDir($path, $root = null)
    {
        if ($root === null) $root = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR;
        return $root . 'uploads' . DIRECTORY_SEPARATOR . $path;
    }

    /**
     * TODO 修改 https 和 http
     * @param $url $url 域名
     * @param int $type 0 返回https 1 返回 http
     * @return string
     */
    public static function setHttpType($url, $type = 0)
    {
        $domainTop = substr($url, 0, 5);
        if ($type) {
            if ($domainTop == 'https') $url = 'http' . substr($url, 5, strlen($url));
        } else {
            if ($domainTop != 'https') $url = 'https:' . substr($url, 5, strlen($url));
        }
        return $url;
    }


    /**
     * 获取图片类型和大小
     * @param string $url 图片地址
     * @param int $type 类型
     * @param bool $isData 是否真实获取图片信息
     * @return array
     */
    public static function getImageHeaders(string $url, $type = 1, $isData = true)
    {
        stream_context_set_default([
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ],
        ]);
        $header['Content-Length'] = 0;
        $header['Content-Type'] = 'image/jpeg';
        if (!$isData) return $header;
        try {
            $header = get_headers(str_replace('\\', '/', self::setHttpType($url, $type)), true);
            if (!isset($header['Content-Length'])) $header['Content-Length'] = 0;
            if (!isset($header['Content-Type'])) $header['Content-Type'] = 'image/jpeg';
        } catch (\Exception $e) {
        }
        return $header;
    }

    /**
     * 本地文件上传
     * @param $fileName
     * @return array|string
     */
    public function uploadLocalFile($fileName = 'file')
    {
        $file = request()->file($fileName);
        $this->autoValidate = true;
        if (!$file) {
            throw new \Exception('上传文件不存在');
        }
        if ($this->autoValidate) {
            try {
                validate([$fileName => $this->imageValidate])->check([$fileName => $file]);
            } catch (ValidateException $e) {
                return $e->getMessage();
            }
        }
        $fileName = Filesystem::disk('public')->putFile($this->uploadPath, $file);
        if (!$fileName) {
            throw new \Exception('图片上传失败');
        }
        $filePath = Filesystem::disk('public')->path($fileName);
        $fileInfo = new File($filePath);
        $url = '/storage/' . $fileName;
        $this->uploadPath = '';
        $this->autoValidate = false;
        return $this->setUploadInfo($url, 1, $fileInfo->getFilename(), self::thumb($url), [
            'Content-Length' => $fileInfo->getSize(),
            'Content-Type' => $fileInfo->getMime(),
            'ext' => $fileInfo->getExtension()
        ]);
    }

    public function uploadOssFile($fileName = 'file', $enableCompression = true)
    {
        $file = request()->file($fileName);
        $this->autoValidate = true;
        if (!$file) {
            throw new \Exception('上传文件不存在');
        }
        $accessKeyId = Config::get('oss.access_key_id');
        $accessKeySecret = Config::get('oss.access_key_secret');
        $endpoint = Config::get('oss.endpoint');
        $bucket = Config::get('oss.bucket');
        $cdnUrl = Config::get('oss.cdn_url');
        if ($this->autoValidate) {
            try {
                validate([$fileName => $this->imageValidate])->check([$fileName => $file]);
            } catch (ValidateException $e) {
                return $e->getMessage();
            }
        }
        try {
            $filePath = $file->getRealPath();
            $ext = $file->getOriginalExtension();
            $originalFileName = $file->md5();
            $fileName = $this->uploadPath . $originalFileName . '.' . $ext;
            
            // 图片压缩处理
            $compressedPath = $filePath;
            $compressionInfo = null;
            
            if ($enableCompression && $this->isImage($ext)) {
                $compressService = new ImageCompressService();
                
                // 检查是否需要压缩
                if ($compressService->needsCompression($filePath)) {
                    logs('开始压缩图片', [
                        'original_path' => $filePath,
                        'original_size' => filesize($filePath),
                        'extension' => $ext
                    ]);
                    
                    // 创建临时压缩文件路径
                    $tempCompressedPath = sys_get_temp_dir() . '/' . uniqid('compressed_') . '.' . $ext;
                    
                    // 获取推荐的压缩设置
                    $settings = $compressService->getRecommendedSettings($filePath);
                    
                    // 执行压缩
                    $compressionInfo = $compressService->compressImage(
                        $filePath,
                        $tempCompressedPath,
                        $settings['quality'],
                        $settings['maxWidth'],
                        $settings['maxHeight'],
                        $ext
                    );
                    
                    if ($compressionInfo['success']) {
                        $compressedPath = $tempCompressedPath;
                        logs('图片压缩成功', [
                            'original_size' => $compressionInfo['original_size'],
                            'final_size' => $compressionInfo['final_size'],
                            'compression_ratio' => $compressionInfo['compression_ratio'] . '%'
                        ]);
                    } else {
                        logs('图片压缩失败，使用原图上传', [
                            'error' => $compressionInfo['error']
                        ],'warning');
                    }
                }
            }
            
            $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $res = $ossClient->uploadFile($bucket, $fileName, $compressedPath);
            
            // 清理临时压缩文件
            if ($compressedPath !== $filePath && file_exists($compressedPath)) {
                unlink($compressedPath);
            }
            
            if ($res['info']['http_code'] !== 200) {
                return 'upload file failed';
            }
            
            $url = $cdnUrl . $fileName;
            
            // 获取最终文件信息
            $finalSize = $compressionInfo && $compressionInfo['success'] ? 
                        $compressionInfo['final_size'] : $file->getSize();
            
            $uploadInfo = $this->setUploadInfo($url, 1, $file->getFilename(), self::thumb($url), [
                'Content-Length' => $finalSize,
                'Content-Type' => $file->getMime(),
                'ext' => $file->getExtension()
            ]);
            
            // 添加压缩信息到返回结果
            if ($compressionInfo && $compressionInfo['success']) {
                $uploadInfo['compression_info'] = [
                    'compressed' => true,
                    'original_size' => $compressionInfo['original_size'],
                    'final_size' => $compressionInfo['final_size'],
                    'compression_ratio' => $compressionInfo['compression_ratio'],
                    'quality' => $compressionInfo['quality']
                ];
            } else {
                $uploadInfo['compression_info'] = [
                    'compressed' => false,
                    'original_size' => $file->getSize(),
                    'final_size' => $file->getSize(),
                    'compression_ratio' => 0
                ];
            }
            
            return $uploadInfo;
            
        } catch (\Exception $e) {
            // 清理可能的临时文件
            if (isset($compressedPath) && $compressedPath !== $filePath && file_exists($compressedPath)) {
                unlink($compressedPath);
            }
            return '请检查oss配置' . $e->getMessage();
        }
    }

    /**
     * 设置返回的数据信息
     * @param string $url
     * @param int $imageType
     * @param string $name
     * @param string $thumbPath
     * @return array
     */
    protected function setUploadInfo(string $url, int $imageType, string $name = '', string $thumbPath = '', array $headerArray = [])
    {
        $headerArray = count($headerArray) ? $headerArray : self::getImageHeaders($url);
        if (is_array($headerArray['Content-Length']) && count($headerArray['Content-Length']) == 2) {
            $headerArray['Content-Length'] = $headerArray['Content-Length'][1];
        }
        if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Type']) == 2) {
            $headerArray['Content-Type'] = $headerArray['Content-Type'][1];
        }
        $info = [
            'name' => str_replace('\\', '/', $name ?: $url),
            'dir' => str_replace('\\', '/', $url),
            'size' => $headerArray['Content-Length'],
            'type' => $headerArray['Content-Type'],
            'time' => time(),
            'thumb_path' => str_replace('\\', '/', $thumbPath ?: $url),
            'image_type' => $imageType,
            'ext' => isset($headerArray['ext']) ? $headerArray['ext'] : ''
        ];
        $uploadInfo = array_merge($this->uploadInfo, $info);
        return $uploadInfo;
    }

    /**
     * 文件上传
     * @param string $fileName 上传文件名
     * @return mixed
     */
    public function file($fileName)
    {
        $file = request()->file($fileName);
        if (!$file) return self::setError('上传文件不存在!');
        if (strtolower($file->getOriginalExtension()) === 'php' || !$file->getOriginalExtension())
            return self::setError('上传文件非法!');
        if ($this->autoValidate) {
            try {
                validate([$fileName => $this->imageValidate])->check([$fileName => $file]);
            } catch (ValidateException $e) {
                return self::setError($e->getMessage());
            }
        };
        $fileName = Filesystem::putFile($this->uploadPath, $file);
        if (!$fileName) return self::setError('图片上传失败!');
        $filePath = Filesystem::path($fileName);
        $fileInfo = new File($filePath);
        $arr = [
            'name' => $fileInfo->getFilename(),
            'dir' => str_replace('\\', '/', $fileName),
            'size' => $fileInfo->getSize(),
            'type' => $fileInfo->getMime(),
            'time' => time(),
            'thumb_path' => '',
            'image_type' => 1,
            'ext' => $fileInfo->getExtension()
        ];
        return self::successful($arr);
    }

    /**
     * 打开图片
     * @param $filePath
     * @return \think\Image
     */
    public function openImage($filePath)
    {
        return \think\Image::open($filePath);
    }


    /**
     * 判断文件是否为图片
     * @param string $extension 文件扩展名
     * @return bool
     */
    private function isImage(string $extension): bool
    {
        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        return in_array(strtolower($extension), $imageExtensions);
    }

    /**
     * 图片压缩
     *
     * @param string $filePath 文件路径
     * @param int $ratio 缩放比例 1-9
     * @param string $pre 前缀
     * @return string 压缩图片路径
     */
    public function thumb($filePath, $ratio = 5, $pre = 's_')
    {
        try {
            $p = str_replace('\\', '/', $filePath);
            $img = $this->openImage($p);
        } catch (\Throwable $e) {
            $dir = dirname($filePath);
            $fileName = basename($filePath);
            return $dir . DIRECTORY_SEPARATOR . $fileName;
        }
        $width = $img->width() * $ratio / 10;
        $height = $img->height() * $ratio / 10;
        $dir = dirname($filePath);
        $fileName = basename($filePath);
        $savePath = $dir . DIRECTORY_SEPARATOR . $pre . $fileName;
        $img->thumb($width, $height)->save($savePath);
        if (substr($savePath, 0, 2) == './') return substr($savePath, 1, strlen($savePath));
        return DIRECTORY_SEPARATOR . $savePath;
    }
}
